import 'dart:math';

// import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
// import 'package:flutter_plugin_record_plus/flutter_plugin_record.dart';
import 'package:ls_work/a_yyt/widget/yyt_play_voice_widget.dart';

import '../../res/gaps.dart';

typedef  OnVoicePlayListener = void Function(String playPath,dynamic playState);


class YYTPlayVoiceUtils{

  List<OnVoicePlayListener> _voiceListeners = [];
  var _hasInit = false;

  void addListener(OnVoicePlayListener listener){
    _voiceListeners.add(listener);
  }

  void removeListener(OnVoicePlayListener listener){
    _voiceListeners.remove(listener);
  }

  // FlutterPluginRecord recordPlugin = new FlutterPluginRecord();
  // AudioPlayer player = AudioPlayer();

  static YYTPlayVoiceUtils? _instance;

  static YYTPlayVoiceUtils get instance  {
    if(_instance==null){
      _instance = YYTPlayVoiceUtils();
    }
    return _instance!;
  }


  Future<void> playVoice(String path) async {
    // recordPlugin.stopPlay();
    // recordPlugin.playByPath(path, type);
    // player.stop();
    // player.play(UrlSource(path));
  }

  void initPlayer() async {
    if(_hasInit){
      return;
    }
    // recordPlugin.init();
    // recordPlugin.responseFromInit.listen((data) {
    //   if (data) {
    //     print("初始化成功");
    //   } else {
    //     print("初始化失败");
    //   }
    // });
    // recordPlugin.responsePlayStateController.listen((data) {
    //   // print("播放路径   " + data.playPath);
    //   // print("播放状态   " + data.playState);
    //   for(var listener in _voiceListeners){
    //     listener(data.playPath,data.playState);
    //   }
    // });
    // player.onPlayerStateChanged.listen((it) {
    //
    //   print("播放状态   " + it.toString());
    //     for(var listener in _voiceListeners){
    //       var source = player.source;
    //       if(source is UrlSource){
    //         listener((source).url,it);
    //       } else if(source is AssetSource){
    //         listener((source as AssetSource).path,it);
    //       }else{
    //         listener("",it);
    //       }
    //
    //     }
    // });

    _hasInit = true;
  }


}

class YYTPlayVoiceWidget extends StatefulWidget  {

  final String url;


  YYTPlayVoiceWidget(this.url);

  @override
  _VoiceWidgetState createState() => _VoiceWidgetState();
}

class _VoiceWidgetState extends State<YYTPlayVoiceWidget>
    with SingleTickerProviderStateMixin {
  double starty = 0.0;
  double offset = 0.0;
  bool isUp = false;
  List<String> _assetList =  [];
  bool isAnimation = false;

  // FlutterPluginRecord? recordPlugin;

  ///播放动画 - 动画控制
  Animation<double>? _animation;
  AnimationController? _controller;
  int interval = 200;

  OnVoicePlayListener? listener;

  @override
  void dispose() {
    YYTPlayVoiceUtils.instance.removeListener(listener!);
    _controller?.dispose();
    super.dispose();
  }

  _animationStop() {
    _controller?.stop();
  }

  _animationStart() {
    _controller?.forward();
  }

  @override
  void initState() {
    super.initState();
    // recordPlugin = FlutterPluginRecord();
    YYTPlayVoiceUtils.instance.initPlayer();
    // listener = ((String playPath,PlayerState playState){
    //
    //   print("播放地址：${widget.url}\n当前播放：${playPath}\n状态：${playState}");
    //   // if(widget.url!=playPath){
    //   //   setState(() {
    //   //     isAnimation = false;
    //   //   });
    //   // }else{
    //   //   if (playState == 'complete') {
    //   //     setState(() {
    //   //       isAnimation = false;
    //   //     });
    //   //   }else{
    //   //     setState(() {
    //   //       isAnimation = true;
    //   //     });
    //   //   }
    //   // }
    //   if(playState==PlayerState.playing){
    //     if(widget.url!=playPath){
    //       setState(() {
    //         isAnimation = false;
    //       });
    //     }else{
    //       setState(() {
    //         isAnimation = true;
    //       });
    //     }
    //   }else{
    //       setState(() {
    //         isAnimation = false;
    //       });
    //   }
    //
    // });
    YYTPlayVoiceUtils.instance.addListener(listener!);

    _assetList.add("assets/left_voice_1.png");
    _assetList.add("assets/left_voice_2.png");
    _assetList.add("assets/left_voice_3.png");

    final int imageCount = _assetList.length;
    final int maxTime = interval * imageCount;

    // 启动动画controller
    _controller = new AnimationController(
        duration: Duration(milliseconds: maxTime), vsync: this);
    _controller?.addStatusListener((AnimationStatus status) {
      if (status == AnimationStatus.completed) {
        _controller?.forward(from: 0.0); // 完成后重新开始
      }
    });

    _animation = new Tween<double>(begin: 0, end: imageCount.toDouble())
        .animate(_controller!)
      ..addListener(() {
        setState(() {});
      });

    _init();

    // ///初始化方法的监听
    // recordPlugin.responseFromInit.listen((data) {
    //   if (data) {
    //     print("初始化成功");
    //   } else {
    //     print("初始化失败");
    //   }
    // });


    // ///播放状态
    // recordPlugin.responsePlayStateController.listen((data) {
    //   print("播放路径   " + data.playPath);
    //   print("播放状态   " + data.playState);
    //   if(widget.url!=data.playPath){
    //     setState(() {
    //       isAnimation = false;
    //     });
    //   }
    //   if (data.playState == 'complete') {
    //     setState(() {
    //       isAnimation = false;
    //     });
    //   }
    //
    //
    // });
  }

  ///初始化语音录制的方法
  void _init() async {
    // recordPlugin.init();
  }

  @override
  Widget build(BuildContext context) {
    List<Widget> images = [];
    if (isAnimation) {
      _animationStart();
      int ix = (_animation?.value.floor()??0) % _assetList.length;
      // 把����������有图片都加载进内容，否则每一帧加载时会卡顿
      for (int i = 0; i < _assetList.length; ++i) {
        if (i != ix) {
          images.add(Image.asset(
            _assetList[i],
            width: 0,
            height: 0,
            color: Colors.white,
          ));
        }
      }
      images.add(
        Image.asset(
          _assetList[ix],
          width: 30,
          height: 30,
          color: Colors.white,
        ),
      );
    } else {
      _animationStop();
    }

    return InkWell(
      onTap: () {
        // setState(() {
        //   isAnimation = true;
        // });
        YYTPlayVoiceUtils.instance.playVoice(widget.url);
        // recordPlugin.playByPath(widget.url, "url");
      },
      child: Container(
        decoration: BoxDecoration(
          color: Colors.transparent,
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: isAnimation
              ? images
              : [
            Image.asset(
              _assetList[2],
              width: 30,
              height: 30,
              color: Colors.white,
            ),
          ],
        ),
      ),
    );
  }
}